# -*- coding: utf-8 -*-
# @Time     :2021/10/25 15:41
# @Author   : master
# @Software : PyCharm


from openpyxl import load_workbook
from tools.read_config import ReadConfig
from tools.project_path import *


class DoExcel():
    @staticmethod
    def get_data(file_name):
        wb = load_workbook(file_name)
        mode = eval(ReadConfig.get_config(case_config_path, 'MODE', 'mode'))
        # te1 = '15029827672'      # 假设是从Excel里拿到的手机号
        test_data = []
        for key in mode:        # 遍历这个存在配置文件里面的字典
            sheet = wb[key]         # 表单名
            if mode[key] == 'all':
                for i in range(2, sheet.max_row + 1):
                    row_data = {}
                    row_data['case_id'] = sheet.cell(
                        i, 2).value              # 行号
                    row_data['url'] = sheet.cell(i, 4).value
                    row_data['header'] = sheet.cell(i, 5).value
                    row_data['data'] = sheet.cell(i, 6).value
                    # if sheet.cell(i, 5).value.find(
                    #         '${tel_1}') == 1:     # 有找到这个字符串
                    #     row_data['data'] = sheet.cell(i, 3).value.repalce('${tel_1}', te1)
                    row_data['title'] = sheet.cell(i, 7).value
                    row_data['http_method'] = sheet.cell(i, 3).value
                    row_data['expected'] = sheet.cell(
                        i, 8).value     # 添加一个期望值到测试数据中去
                    row_data['sheet_name'] = key
                    test_data.append(row_data)
            else:
                for case_id in mode[key]:        #
                    row_data = {}    # 字典
                    row_data['case_id'] = sheet.cell(
                        case_id + 1, 2).value  # 行号
                    row_data['url'] = sheet.cell(case_id + 1, 4).value
                    row_data['header'] = sheet.cell(case_id + 1, 5).value
                    row_data['data'] = sheet.cell(case_id + 1, 6).value

                    row_data['title'] = sheet.cell(case_id + 1, 7).value
                    row_data['http_method'] = sheet.cell(case_id + 1, 3).value
                    row_data['expected'] = sheet.cell(
                        case_id + 1, 8).value  # 添加一个期望值到测试数据中去
                    row_data['sheet_name'] = key
                    test_data.append(row_data)
        return test_data

    def write_back(self, file_name, sheet_name, i, result, TestResult, response_time):           # 写回数据
        wb = load_workbook(file_name)
        sheet = wb[sheet_name]
        sheet.cell(i, 9).value = result
        sheet.cell(i, 10).value = TestResult
        sheet.cell(i, 11).value = response_time
        wb.save(file_name)                                     # 保存结果


if __name__ == '__main__':
    test_data = DoExcel().get_data('../test_data/test_data.xlsx')
    print(test_data)
